<template>
  <div class="change-settings">
    <BasicCard style="margin-bottom: 20px">
      <BasicVxeForm ref="formRef" :formOptions="formOptions"></BasicVxeForm>
      <BasicVxeTable ref="gridRef" v-bind="gridOption"> </BasicVxeTable>
    </BasicCard>
    <BasicCard style="margin-bottom: 20px">
      <BasicVxeTable ref="gridRefChange" v-bind="gridOptionChange"> </BasicVxeTable>
    </BasicCard>
  </div>
</template>
<script setup lang="ts">
  import { valueZhuaneFloat } from '@/utils/custom/index'
  // import { DetailedReportRowVO, ChangeStatisticsRowVO } from '../types'
  // import { DetailedReportTableColumns, ChangeStatisticsTableColumns } from '../data'

  import {
    postSheZhiBianGenList,
    getZiDingYiBaoBiaos,
    getShiShiZhuangTaiQuanJi,
    getwuLiaoAndJiTai
  } from '@/api/shengChanJianShi'
  import dayjs from 'dayjs'

  const props = defineProps({
    statusCode: String,
    processName: String
  })

  const { t } = useI18n()
  const gridRef = ref<BasicGridInstance>()
  const gridRefChange = ref<BasicGridInstance>()

  interface FormV0 {
    pageType: 'settings' | 'process'
    reportId: string
    material: string[]
  }

  const pageTypeEnum = {
    settings: { text: '基础设定', value: 2 },
    process: { text: '工艺设定', value: 3 }
  }
  const formRef = ref<BasicFormInstance>()
  const formData = ref({
    pageType: 'settings',
    reportId: ''
  })
  const formOptions = reactive<BasicFormProps<FormV0>>({
    titleWidth: 60,
    padding: false,
    data: {
      pageType: 'settings'
    },
    items: [
      {
        field: 'pageType',
        span: 4,
        itemRender: {
          name: 'ElRadioGroup',
          options: [
            { label: t('custom.基础设定'), value: 'settings' },
            { label: t('custom.工艺设定'), value: 'process' }
          ],
          events: {
            change: (params, e) => {
              formData.value = params.data
              if (e) {
                // 切换对应的table
                handleInitData()
              }
            },
            VnodeMounted(params) {
              // 初始化触发时间更新
              formRef.value?.emitter.emit('field:pageType:change', params)
            }
          }
        }
      },
      {
        span: 2,
        itemRender: {
          name: 'ElButtons',
          children: [
            {
              type: 'primary',
              content: t('system.查询'),
              events: {
                click: (params) => {
                  handleSearch(params)
                }
              }
            }
          ]
        }
      }
    ]
  })

  // 详细报表
  const gridOption = reactive<BasicGridProps>({
    extraConfig: {
      title: t('custom.详细报表'),
      isCustom: false,
      isExport: true,
      isFilterAndSort: false
    }, // 拓展的配置
    id: `change-settings-${props.statusCode}-detail`, // id用于缓存,务必配置
    toolbarConfig: {}, // 工具栏
    maxHeight: 500,
    exportConfig: {
      filename: '数据表'
    },
    loading: true
  })

  // 改动次数统计
  const gridOptionChange = reactive<BasicGridProps>({
    loading: true,
    extraConfig: {
      title: t('custom.改动次数统计'),
      isCustom: true,
      isExport: false,
      isFilterAndSort: false
    }, // 拓展的配置
    id: `change-settings-${props.statusCode}-change`, // id用于缓存,务必配置
    toolbarConfig: {}, // 工具栏
    maxHeight: 500,
    exportConfig: {
      filename: '数据表'
    },
    data: [],
    columns: []
  })

  const handleInitFunc = () => {
    Promise.all([getAllData(), getMaterialsMachineryData()]).then(() => {
      getDetailedReportList()
    })
  }

  // 初始化 获取数据
  const customDict = ref<any>()
  const customList = ref<any>([])
  const handleInitData = () => {
    getZiDingYiBaoBiaos({
      craftNodeName: props.processName,
      pageName: props.processName + pageTypeEnum[formData.value.pageType].text + '设置变更'
    }).then((res: any) => {
      customList.value = res
      customDict.value = customList.value.find((val) => {
        return val.defaultDisplayFlag === true
      })

      if (customDict.value === undefined) {
        handleInitFunc()
      } else {
        let columnArr = customList.value.customReportDetail.map((value) => {
          return {
            title: value.columnName,
            minWidth: 80,
            field: value.columnCode,
            visible: true,
            align: 'center'
          }
        })
        gridOption.columns = handleDetailedColumns(columnArr)
        gridOptionChange.columns = handleChangeColumns(columnArr)
        handleInitFunc()
      }
    })
  }

  // 获取采集所有参数
  const collectList = ref<any>([])
  const getAllData = () => {
    return new Promise((resolve) => {
      getShiShiZhuangTaiQuanJi(props.processName).then((res: any) => {
        let dict = res.find((value) => {
          return value.firstTypeName === formData.value.pageType
        })
        collectList.value = dict.metaCode
        if (customDict.value === undefined) {
          let tabTitle = collectList.value.map((value) => {
            return {
              title: value.metaName,
              field: value.metaCode,
              minWidth: 80,
              visible: true,
              align: 'center'
            }
          })
          gridOption.columns = handleDetailedColumns(tabTitle)
          gridOptionChange.columns = handleChangeColumns(tabTitle)
        }
        resolve(res)
      })
    })
  }

  // 获取物料和机台列表
  const machinerySelectedValue = ref<any>()
  const machineryList = ref<any>()
  const processList = ref<any>()
  const midList = ref<any>()
  const getMaterialsMachineryData = () => {
    return new Promise((resolve) => {
      getwuLiaoAndJiTai(props.processName).then((res: any) => {
        if (res && res.length > 0) {
          const backJson = res

          // 收集所有childNodes并过滤出选中项
          const selectedItems: any = []
          const nameArr: any = []

          backJson.forEach((item, index) => {
            // 处理item的默认值
            item.text = item.text || '未设置品种'
            item.id = item.id || `10000${index}` // 修复：使用item.id而非item.text进行判断

            // 处理子节点
            if (item.childNodes && Array.isArray(item.childNodes)) {
              item.childNodes.forEach((child: any) => {
                selectedItems.push(child)
                if (child.check) {
                  nameArr.push(child.text)
                }
              })
            }
          })

          // 正确排序机台列表（按text字符串排序）
          const jiTaiArr = [...selectedItems].sort((a, b) => a.text.localeCompare(b.text, 'zh-CN'))

          // 提取机台ID数组
          const idArr = jiTaiArr.map((item: any) => item.id)

          // 设置组件状态
          machineryList.value = jiTaiArr
          processList.value = backJson
          midList.value = idArr
          // this.jitaiArrayCode2 = idArr

          machinerySelectedValue.value =
            nameArr.length === 2
              ? nameArr.join()
              : nameArr.sort((a, b) => a.localeCompare(b, 'zh-CN')).join('-')

          resolve(res)
        }
      })
    })
  }

  // 获取表格数据
  const getDetailedReportList = () => {
    postSheZhiBianGenList({
      machineDocumentId: midList.value,
      begin: '2025-07-06 00:00:00',
      end: '2025-07-07 23:59:59',
      paramFirstType: pageTypeEnum[formData.value.pageType].value
    }).then((res: any) => {
      gridOption.loading = false
      gridOptionChange.loading = false
      // 统计报表数据
      let tongJiArr: any = []
      midList.value &&
        midList.value.forEach((value) => {
          let dict: any = {}
          let item = machineryList.value.find((value2) => {
            return value === value2.id
          })
          dict.machineName = item.text
          collectList.value.forEach((value1) => {
            dict[value1.metaCode] = 0
          })
          tongJiArr.push(dict)
        })
      gridOptionChange.data = tongJiArr

      // 详细报表数据
      gridOption.data = res.map((value) => {
        let dict = JSON.parse(value.parameterJson)

        return {
          machineName: value.machineName,
          machineDocumentId: value.machineDocumentId,
          machineNo: value.machineNo,
          paraType: value.paraType,
          originTime:
            value.originTime === undefined || value.originTime === ''
              ? ''
              : dayjs(value.originTime).format('YYYY-MM-DD HH:mm:ss'),
          ...valueZhuaneFloat(dict, 4)
        }
      })
    })
  }

  const handleDetailedColumns = (arr) => {
    return [
      {
        title: '机台号',
        minWidth: 100,
        field: 'machineName',
        className: 'name-col',
        visible: true,
        fixed: 'left',
        align: 'center'
      },
      {
        title: '发生时间',
        field: 'originTime',
        minWidth: 150,
        visible: true,
        fixed: 'left',
        align: 'center'
      },
      ...arr
    ]
  }

  const handleChangeColumns = (arr) => {
    return [
      {
        title: '机台号',
        minWidth: 100,
        field: 'machineName',
        visible: true,
        fixed: 'left',
        align: 'center'
      },
      ...arr
    ]
  }

  onMounted(() => {
    // 初始化获取列数据与表格数据
    handleInitData()
  })
</script>
<style scoped lang="scss"></style>
